﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using FZKJ.COMMON;
using FZKJ.ZHXJ.Models;
using System.Text;
using Newtonsoft.Json;
using System.Data;
using System.Transactions;

namespace FZKJ.ZHXJ.Controllers
{
    [FZKJ.ZHXJ.FilterConfig.LoginCheckFilter(IsCheck = false)]
    public class WeChatController : Controller
    {
        public static readonly string Appid = ConfigurationManager.AppSettings["wxappid"];//微信公众号的appid
        public static readonly string Secret = ConfigurationManager.AppSettings["wxappsecret"]; //微信公众号的secret
        private static readonly string url = ConfigurationManager.AppSettings["url"]; //微信公众号的secret
        public ActionResult Activity()
        {
            string openid = GetOpenid();
            //获取openid失败
            if (openid == "-1")
            {
                return Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Appid + "&redirect_uri=http%3a%2f%2fwww.thzhxj.com%2fWeChat%2fActivity?type=0&response_type=code&scope=snsapi_base&state=123#wechat_redirect");
            }
            else
            {
                BLL.buss_members member = new BLL.buss_members();
                DataTable dt = member.GetList(" openid='" + openid + "' ").Tables[0];
                Session["openid"] = openid;
                if (dt.Rows.Count > 0)//录入过信息，直接跳转到首页
                {
                    return Redirect("Action");
                }
                else//首次登陆，跳转到录入信息页面
                    return Redirect("Index");
            }
        }
        /// <summary>
        /// 获取openid
        /// </summary>
        /// <returns></returns>
        public string GetOpenid()
        {
            try
            {
                string code = Request.QueryString["code"];
                if (string.IsNullOrEmpty(code)) return "-1";
                string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", Appid, Secret, code);

                HttpHelper htphlper = new HttpHelper();
                HttpItem htpitm = new HttpItem
                {
                    URL = url,
                    Method = "GET"
                };

                HttpResult re = htphlper.GetHtml(htpitm);
                JsonObject obj = new JsonObject(re.Html);
                if (obj["errcode"] == null)
                {
                    string openid = obj["openid"].Value;
                    url = $" https://api.weixin.qq.com/sns/userinfo?access_token={obj["access_token"].Value}&openid={obj["openid"].Value}&lang=zh_CN";
                    htphlper = new HttpHelper();
                    htpitm = new HttpItem
                    {
                        URL = url,
                        Method = "GET"
                    };

                    re = htphlper.GetHtml(htpitm);

                    string res = GB2312ToUTF8(re.Html);
                    byte[] by = System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(re.Html);
                    string str = System.Text.Encoding.UTF8.GetString(by);

                    obj = new JsonObject(System.Text.Encoding.UTF8.GetString(by));
                    if (obj["errcode"] == null)
                    {
                        Session["headImg"] = obj["headimgurl"].Value;
                        Session["nickName"] = obj["nickname"].Value;
                        Session["city"] = obj["city"].Value;
                        Session["country"] = obj["country"].Value;
                        Session["province"] = obj["province"].Value;
                    }
                    Session["openid"] = openid;
                    return openid;
                }
                return "-1";
            }
            catch (Exception ex)
            {
                return "-1";
            }
        }


        private string GB2312ToUTF8(string str)
        {
            try
            {
                Encoding utf8 = Encoding.UTF8;
                Encoding gb2312 = Encoding.GetEncoding("GB2312");
                byte[] unicodeBytes = gb2312.GetBytes(str);
                byte[] asciiBytes = Encoding.Convert(gb2312, utf8, unicodeBytes);
                char[] asciiChars = new char[utf8.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
                utf8.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
                string result = new string(asciiChars);
                return result;
            }
            catch
            {
                return "";
            }
        }

        public ActionResult MemberIndex(string typs = "")
        {

            string openid = "";
            SaveLog.Info("typs=" + typs, null);
            if (string.IsNullOrWhiteSpace(typs))
            {
                openid = GetOpenid();
                if (openid == "-1")
                {
                    return Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Appid + "&redirect_uri=http%3a%2f%2f" + url + "%2fWeChat%2fMemberIndex?type=2&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
                }
            }
            else
            {
                openid = Session["openid"].ToString();
            }
            BLL.buss_members member = new BLL.buss_members();
            DataTable dt = member.GetList(" openid='" + openid + "' ").Tables[0];
            Session["openid"] = openid;
            SaveLog.Info("openid=" + openid, null);
            if (dt.Rows.Count > 0)//录入过信息，直接跳转到首页
            {
                try
                {
                    SaveLog.Info("headImg=" + Session["headImg"].ToString(), null);
                    var model = member.GetModel(dt.Rows[0]["code"].ToString());
                    model.headImg = Session["headImg"].ToString();
                    model.nickName = Session["nickName"].ToString();
                    model.city = Session["province"] + " " + Session["city"];
                    model.country = Session["country"].ToString();
                    ViewBag.JiFen = model.point;
                    member.Update(model);
                }
                catch (Exception ex)
                {
                    SaveLog.Error(ex.Message, ex);
                }
                ViewBag.src = Session["headImg"].ToString();
                return View();
            }
            else//首次登陆，跳转到录入信息页面
                return Redirect("Index?type=2");
            return View();
        }


        //
        // GET: /WeChat/

        public ActionResult Index(string type)
        {
            ViewBag.type = type;
            return View();
        }
        [HttpPost]
        public string Register(string json)
        {
            var result = new ResultInfo(false);
            try
            {
                var obj = JsonConvert.DeserializeObject<Register>(json);
                var code = new BLL.buss_smsinfo().GetModel(obj.token);
                var mobiles = new BLL.buss_members().GetModelList(" mobile='" + obj.mobile + "'");
                if (mobiles.Count > 0)
                {
                    result.IsSucceed = false;
                    result.Message = "该手机号已注册";
                }
                else
                {
                    if (code == null)
                    {
                        result.IsSucceed = false;
                        result.Message = "验证码不存在";
                    }
                    else
                    {
                        if (code.validatecode != obj.code)
                        {
                            result.IsSucceed = false;
                            result.Message = "验证码不正确";
                        }
                        else
                        {
                            SaveLog.Info(" Session[openid]=" + Session["openid"].ToString(), null);
                            var member = new Model.buss_members
                            {
                                code = GenerateCode.GetCode(),
                                id = Guid.NewGuid().ToString().Replace("-", "").ToLower(),
                                name = obj.name,
                                mobile = obj.mobile,
                                openid = Session["openid"].ToString(),
                                password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(obj.password, "MD5")
                            };
                            new BLL.buss_members().Add(member);
                            result.IsSucceed = true;
                            result.Message = "注册成功";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Message = "注册失败";
                SaveLog.Error(ex.Message, ex);
            }
            return JsonConvert.SerializeObject(result);

        }


        public ActionResult Login()
        {
            return View();
        }
        public ActionResult Action()
        {
            //Session["openid"] = "oY0Xd0sIVykd3viWfvkjPKLLv8Xc";
            //var list = new BLL.buss_members().GetModelList(" openid='oY0Xd0sIVykd3viWfvkjPKLLv8Xc'");
            var list = new BLL.buss_members().GetModelList($" openid='{Session["openid"]}'");
            if (list.Count == 0)
            {
                return Redirect("Index");
            }
            else
            {
                var isExist = new BLL.buss_rescue().GetModelList(" memberid='" + list[0].id + "'");
                string card = isExist.Count > 0 ? isExist[0].rescuecard : "";
                var dt = new BLL.buss_members().GetMemberCard(card);
                ViewData["dt"] = dt;
                ViewBag.isExist = isExist.Count > 0;
                return View();
            }
        }
        /// <summary>
        /// 发送短信验证码
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public string SendCodeByRegister(string mobile)
        {
            var result1 = new ResultInfo(false);

            try
            {
                var mobiles = new BLL.buss_members().GetModelList(" mobile='" + mobile + "'");
                if (mobiles.Count > 0)
                {
                    result1.IsSucceed = false;
                    result1.Message = "该手机号已注册";
                }
                else
                {
                    result1 = SendMessageCode.SendByInterface(mobile, 1);
                }
            }
            catch (Exception ex)
            {
                result1.IsSucceed = false;
                result1.Message = "发送失败";
            }
            return JsonConvert.SerializeObject(result1);
        }
        /// <summary>
        /// 发送短信验证码
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public string SendCodeByLogin(string mobile)
        {
            var result1 = new ResultInfo(false);
            try
            {
                result1 = SendMessageCode.SendByInterface(mobile, 2);
            }
            catch (Exception ex)
            {
                result1.IsSucceed = false;
                result1.Message = "发送失败";
            }
            return JsonConvert.SerializeObject(result1);
        }
        [HttpPost]
        public string ActivityZHXJ(string json)
        {
            var result = new ResultInfo(false);


            try
            {
                var currentMember = new BLL.buss_members().GetModelList($" openid='{Session["openid"]}'");
                //var currentMember = new BLL.buss_members().GetModelList(" openid='oY0Xd0sIVykd3viWfvkjPKLLv8Xc'");
                if (currentMember.Count == 0)
                {
                    result.IsSucceed = false;
                    result.Message = "暂未注册，请先注册之后再激活卡";
                }
                else
                {
                    var member = JsonConvert.DeserializeObject<Model.buss_members>(json);
                    currentMember[0].name = member.name;
                    currentMember[0].sex = member.sex;
                    currentMember[0].mobile = member.mobile;
                    currentMember[0].cardno = member.cardno;
                    currentMember[0].bloodType = member.bloodType;
                    currentMember[0].illnesshistory = member.illnesshistory;
                    currentMember[0].emergencycontact = member.emergencycontact;
                    currentMember[0].emergencycontactmobile = member.emergencycontactmobile;
                    var car = JsonConvert.DeserializeObject<Model.buss_memberCar>(json);
                    var card = JsonConvert.DeserializeObject<Card>(json);
                    var policy = JsonConvert.DeserializeObject<Model.buss_insurance>(json);
                    member.id = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                    car.memberId = currentMember[0].id;
                    policy.memberid = currentMember[0].id;
                    var list = new BLL.buss_card().GetModelList("cardno='" + card.card + "'");
                    var policys = new BLL.buss_policy().GetModelList(" policynumber='" + policy.policynumber + "'");
                    if (policys.Count == 0)
                    {
                        result.IsSucceed = false;
                        result.Message = "保单号不存在，请联系会员卡销售人员";

                    }
                    else
                    {
                        if (list.Count == 0)
                        {
                            result.IsSucceed = false;
                            result.Message = "不存在该卡号";
                        }
                        else
                        {
                            list = list.Where(p => p.activationstate == 0).ToList();
                            if (list.Count == 0)
                            {
                                result.IsSucceed = false;
                                result.Message = "该卡号不是处于待激活状态";
                            }
                            else
                            {
                                var m = list[0];
                                //if (m.password != System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(card.password, "MD5"))
                                //{
                                //    result.IsSucceed = false;
                                //    result.Message = "密码错误";
                                //}
                                //else
                                //{
                                m.activationstate = 1;
                                new BLL.buss_card().Update(m);
                                policy.id = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                                var member_card = new Model.buss_rescue
                                {
                                    id = Guid.NewGuid().ToString().ToLower(),
                                    memberid = currentMember[0].id,
                                    rescuecard = m.cardno,
                                    rescuestart = m.starttime,
                                    rescueend = m.endtime
                                };
                                member.code = GenerateCode.GetCode();
                                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
                                {
                                    new BLL.buss_rescue().Add(member_card);
                                    new BLL.buss_members().Update(currentMember[0]);
                                    new BLL.buss_insurance().Add(policy);
                                    new BLL.buss_memberCar().Add(car);
                                    scope.Complete();
                                }
                                result.IsSucceed = true;
                                result.Message = "输入信息成功";
                                //}
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                result.IsSucceed = false;
                result.Message = "激活失败";
                //PublicClass.AddLog("操作", exception.Message);
            }
            return JsonConvert.SerializeObject(result);
        }
        [HttpPost]
        public string Login(string json)
        {
            var result = new ResultInfo(false);
            try
            {
                var currentMember = new BLL.buss_members().GetModelList(" openid='" + Session["openid"].ToString() + "'");
                if (currentMember.Count == 0)
                {
                    result.IsSucceed = false;
                    result.Message = "暂未注册，请先注册在登陆";
                }
                var obj = JsonConvert.DeserializeObject<Register>(json);
                //var code = new BLL.buss_smsinfo().GetModel(obj.token);
                //if (code == null)
                //{
                //    result.IsSucceed = false;
                //    result.Message = "验证码不存在";
                //}
                //else
                //{
                //if (code.validatecode != obj.code)
                //{
                //    result.IsSucceed = false;
                //    result.Message = "验证码不正确";
                //}
                //var users = currentMember[0];
                //if (users.mobile != obj.mobile)
                //{
                //    result.IsSucceed = false;
                //    result.Message = "手机号码与微信不匹配";
                //}
                //else
                //{
                //    users.openid = Session["openid"].ToString();
                //    new BLL.buss_members().Update(users);
                //    result.IsSucceed = true;
                //    result.Message = "登陆成功";
                //}
                //}

                var users = new BLL.buss_members().GetModelList(" mobile='" + obj.mobile + "'");
                if (users.Count == 0)
                {
                    result.IsSucceed = false;
                    result.Message = "用户不存在";
                }
                else
                {
                    var model = users[0];
                    if (model.password != System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(obj.password, "MD5"))
                    {
                        result.IsSucceed = false;
                        result.Message = "用户密码错误";
                    }
                    else
                    {
                        model.lastLoginTime = DateTime.Now;
                        new BLL.buss_members().Update(model);
                        result.IsSucceed = true;
                        result.Message = "登陆成功";
                    }
                }
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Message = "登录失败";
            }
            return JsonConvert.SerializeObject(result);

        }

        public ActionResult ActivityCar()
        {
            string openid = Session["openid"].ToString();
            var member = new BLL.buss_members();
            DataTable dt = member.GetList(" openid='" + openid + "' ").Tables[0];
            Session["openid"] = openid;
            SaveLog.Info("openid=" + openid, null);
            if (dt.Rows.Count > 0)//录入过信息，直接跳转到首页
            {
                return View();
            }
            else//首次登陆，跳转到录入信息页面
                return Redirect("Index?type=1");
            return View();
        }
        [HttpPost]
        public string ActivityCars(string json)
        {
            var result = new ResultInfo(false);
            try
            {
                var model = JsonConvert.DeserializeObject<Model.buss_vehicle>(json);
                var list = new BLL.buss_vehicle().GetModelList(" carowner='" + model.carowner + "' and carmodel='" + model.carmodel + "' and licenseplate='" + model.licenseplate + "' and drivingnumber='" + model.drivingnumber + "' and enginenumber='" + model.enginenumber + "' and pedestal='" + model.pedestal + "' and mobile='" + model.mobile + "'");
                var currentMember = new BLL.buss_members().GetModelList(" openid='" + Session["openid"] + "'");
                if (currentMember.Count > 0)
                {
                    if (list.Count == 0)
                    {
                        result.IsSucceed = false;
                        result.Message = "车辆不存在";
                    }
                    else
                    {
                        foreach (var item in list)
                        {
                            item.activityState = 1;
                            item.option1 = currentMember[0].id;
                            new BLL.buss_vehicle().Update(item);
                        }
                        result.IsSucceed = true;
                        result.Message = "激活成功";
                    }
                }
                else
                {
                    result.IsSucceed = false;
                    result.Message = "暂未登录";
                }
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Message = ex.Message;
            }
            return JsonConvert.SerializeObject(result);

        }

        public ActionResult ActivityIndex(string typs = "")
        {
            string openid = "";
            if (string.IsNullOrWhiteSpace(typs))
            {
                openid = GetOpenid();
                if (openid == "-1")
                {
                    return Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Appid + "&redirect_uri=http%3a%2f%2f" + url + "%2fWeChat%2fMemberIndex?type=2&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
                }
            }
            else
            {
                openid = Session["openid"].ToString();
            }
            BLL.buss_members member = new BLL.buss_members();
            DataTable dt = member.GetList(" openid='" + openid + "' ").Tables[0];
            Session["openid"] = openid;
            SaveLog.Info("openid=" + openid, null);
            if (dt.Rows.Count > 0)//录入过信息，直接跳转到首页
            {
                try
                {
                    SaveLog.Info("headImg=" + Session["headImg"].ToString(), null);
                    var model = member.GetModel(dt.Rows[0]["code"].ToString());
                    model.headImg = Session["headImg"].ToString();
                    model.nickName = Session["nickName"].ToString();
                    model.city = Session["province"] + " " + Session["city"];
                    model.country = Session["country"].ToString();
                    member.Update(model);
                }
                catch (Exception ex)
                {
                    SaveLog.Error(ex.Message, ex);
                }
                return View();
            }
            else
                return Redirect("Index?type=1");
            return View();
        }

        public ActionResult Service()
        {
            return View();
        }

        public ActionResult UPToGlobal()
        {
            var currentMember = new BLL.buss_members().GetModelList(" openid='" + Session["openid"] + "'");
            ViewBag.model = new Model.buss_members();
            ViewBag.IsGrade = false;
            if (currentMember.Count > 0)
            {
                ViewBag.IsGrade = currentMember[0].isgloabl == 0 || currentMember[0].isgloabl == 1;
                ViewBag.model = currentMember[0];
            }
            return View();
        }
        [HttpPost]
        public string UpgradeCard(string json)
        {
            var result = new ResultInfo(false);
            try
            {
                var currentMember = new BLL.buss_members().GetModelList(" openid='" + Session["openid"] + "'");
                var m = JsonConvert.DeserializeObject<Model.buss_members>(json);
                var m1 = JsonConvert.DeserializeObject<Model.buss_memberCar>(json);
                var m2 = JsonConvert.DeserializeObject<Model.buss_insurance>(json);
                if (currentMember.Count > 0)
                {
                    var model = new Model.buss_cardupgrade
                    {
                        requestTime = DateTime.Now,
                        dealResult = "0",
                        userId = currentMember[0].id
                    };
                    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
                    {
                        new BLL.buss_cardupgrade().Add(model);
                        currentMember[0].isgloabl = 0;
                        currentMember[0].name = m.name;
                        currentMember[0].sex = m.sex;
                        currentMember[0].cardno = m.cardno;
                        currentMember[0].bloodType = m.bloodType;
                        currentMember[0].illnesshistory = m.illnesshistory;
                        currentMember[0].emergencycontact = m.emergencycontact;
                        currentMember[0].emergencycontactmobile = m.emergencycontactmobile;
                        var car=new BLL.buss_memberCar().GetModelList(" memberId='"+currentMember[0].id+"'");
                        if (car.Count > 0)
                        {
                            car[0].VIN = m1.VIN;
                            car[0].numberplate = m1.numberplate;
                            car[0].driving = m1.driving;
                        }
                        var policy=new BLL.buss_insurance().GetModelList(" memberId='"+currentMember[0].id+"'");
                        if (policy.Count > 0)
                        {
                            policy[0].company = m2.company;
                            policy[0].insureanceAgent = m2.insureanceAgent;
                            policy[0].policynumber = m2.policynumber;
                        }

                        new BLL.buss_memberCar().Update(car[0]);
                        new BLL.buss_insurance().Update(policy[0]);
                        new BLL.buss_members().Update(currentMember[0]);
                        scope.Complete();
                    }

                    result.IsSucceed = true;
                    result.Message = "申请成功";
                }
                else
                {
                    result.IsSucceed = false;
                    result.Message = "暂未登录";

                }
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Message = ex.Message;
            }
            return JsonConvert.SerializeObject(result);
        }

        public ActionResult Protocol()
        {
            return View();
        }
    }
    public class Register
    {
        public string name { get; set; }
        public string token { get; set; }
        public string code { get; set; }
        public string mobile { get; set; }
        public string option1 { get; set; }
        public string password { get; set; }
    }
}
